<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2020/2/5
 * Time: 16:27
 */

namespace App\Http\Api\V1\Blls;

use App\Exceptions\UserException;
use App\Http\Common\Facade\AttachmentFacade;
use App\Http\Common\Helper\LogHelper;
use App\Http\Common\Service\Third\Ali\AliUploadService;
use Illuminate\Http\UploadedFile;

class AttachmentBll
{
    /**
     * 上传图片文件
     * @param UploadedFile $sourceImage
     * @return array
     * @throws UserException
     */
    public static function uploadImg($sourceImage)
    {
        if(!$sourceImage->isValid()) {
            throw new UserException('需要上传正确的图片文件');
        }
        $clientName = $sourceImage->getClientOriginalName();    //客户端文件名称..
        $extension = $sourceImage->getClientOriginalExtension();   //上传文件的后缀

        $filename = md5(date('ymdhis') . $clientName) . "." . $extension;
        $fileDir = getUploadDir() . date('Ymd') . '/';    //时间目录
        $relativeFile = $fileDir . $filename;

        $sourceImage->move($fileDir, $filename);    //把缓存文件移动到指定文件夹
        $dest = '/recognition/upload/' . date('Ymd') . '/' . $filename;
        try {
            $fileUrl = (new AliUploadService())->uploadFile($dest, $relativeFile);
        } catch (\Exception $e) {
            LogHelper::warning('图片上传失败');
            $fileUrl = '';
        }
        $attachmentData = [
            'url' => $fileUrl,
            'path' => $relativeFile,
        ];
        $attachment = AttachmentFacade::save($attachmentData);
        return [ $relativeFile, $fileUrl, $attachment->id ];
    }
}